package com.dream.auth.controller;

import com.dream.auth.service.IOauth2Service;
import com.dream.auth.web.service.TokenService;
import com.dream.core.core.domain.AjaxResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 登录验证
 *
 * @author dream
 */
//@RestController
@Controller
@SessionAttributes({"authorizationRequest"})
public class SsoAuthController {
     @Autowired
     private IOauth2Service oauth2Service;
     @Autowired
     private TokenEndpoint tokenEndpoint;
     @Autowired
     private AuthorizationEndpoint authorizationEndpoint;
     @Autowired
     private ClientDetailsService clientDetailsService;
     @Autowired
     private TokenService tokenService;
    @RequestMapping("/oauth2/confirm_access")
    public ModelAndView getAccessConfirmation(Map<String, Object> model, HttpServletRequest request) throws Exception {
        AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest");
        ModelAndView view = new ModelAndView();
        view.setViewName("oauth2/grant");
        String tan=request.getHeader("tan");
        System.out.println("---------------tan:"+tan+"-------------------");
        System.out.println(request.getRequestURL());
        String token = request.getHeader("Authorization");
        view.addObject("clientId", authorizationRequest.getClientId());
        view.addObject("appName", "xxx");
        view.addObject("scopes", authorizationRequest.getScope());
        view.addObject("authorizeUri", request.getContextPath()+"/oauth/authorize");
        return view;
    }
    /*@Autowired
    OAuth2RestTemplate oAuth2RestTemplate;*/
    /*@RequestMapping({"/oauth/confirm_access"})
    @ResponseBody
    public AjaxResult getAccessConfirmation(HttpServletRequest request) throws Exception {
        AjaxResult ajax = AjaxResult.success();
        String client_id = request.getParameter("client_id");
        List<Oauth2Client> clients1 = oauth2Service.getOauth2ClientByClientId(client_id);
        if (clients1 == null || clients1.size() == 0) {
            ajax.put("msg", "clientId无效");
            return ajax;
        }
        Oauth2Client client = clients1.get(0);
        List<String> scopeList = Arrays.asList(client.getScope().split(","));
        ajax.put("client_id", client.getClientId());
        ajax.put("response_type", client.getGrantType());
        ajax.put("redirect_uri", client.getRedirectUrl());
        ajax.put("clientName", client.getClientName());
        ajax.put("scope", scopeList);
        return ajax;
    }*/

   /* @RequestMapping({"/oauth/authorize"})
    @ResponseBody
    public AjaxResult authorize(@RequestParam Map<String, String> parameters, SessionStatus sessionStatus, Principal principal, HttpServletRequest request) {
        AjaxResult ajax = AjaxResult.success();
        String clientId = parameters.get("client_id");
        String redirectUri = parameters.get("redirect_uri");
        Set<String> responseTypes = OAuth2Utils.parseParameterList(parameters.get("response_type"));
        if (StringUtils.isEmpty(clientId)) {
            ajax = AjaxResult.error("找不到客户端");
            return ajax;
        }
        if (StringUtils.isEmpty(redirectUri)) {
            ajax = AjaxResult.error("找不到回调地址");
            return ajax;
        }
        if (!responseTypes.contains("token") && !responseTypes.contains("code")) {
            ajax = AjaxResult.error("不支持的授权类型");
            return ajax;
        }
        ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
        List<String> scopeList = new ArrayList<>(Arrays.asList(parameters.get("scope").split(",")));
        if (!DreamOAuth2Utils.isValidateScope(scopeList, client.getScope())) {
            ajax = AjaxResult.error("无效的scope");
            return ajax;
        }
        if (responseTypes.contains("code")) {
            String url = DreamOAuth2Utils.getSuccessfulRedirect(parameters, (Authentication) principal);
            ajax.put("returnUrl", url);
        }
        ajax.put("token", request.getHeader("Authorization"));
        return ajax;
    }*/

    /*@RequestMapping(value = "/oauth/token", method = RequestMethod.POST)
    public AjaxResult postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        AjaxResult ajax = AjaxResult.success();
        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        if (oAuth2AccessToken != null) {
            Oauth2TokenDto oauth2TokenDto = Oauth2TokenDto.builder()
                    .token(oAuth2AccessToken.getValue())
                    .refreshToken(oAuth2AccessToken.getRefreshToken().getValue())
                    .expiresIn(oAuth2AccessToken.getExpiresIn())
                    .tokenHead("Bearer ").build();
            ajax.put("data", oauth2TokenDto);
        } else {
            ajax.put("data", null);
        }
        return ajax;
    }*/
}
